#include "User.h"
#include <stdio.h>
#include <conio.h>
#include <WinSock2.h>

User::User() :connOK(0)
{ 
}

User::~User(void)
{
	//closesocket(sock);
	endTalk();
}

char* User::getName() 
{
	return name;
}

void User::setName(char *username)
{
	strcpy(name, username);
}

char* User::getIp() 
{
	return inet_ntoa(addr.sin_addr);
}

DWORD WINAPI wait_for_msg(LPVOID lp)
{
	User *user = (User*)lp;
	//SOCKET sock = user->sock;
	while(true)
	{
		if(!user->connOK)
			continue;
		int nrecv;
		char recvBuff[LENGTH];
		nrecv = recv(user->sock, recvBuff, LENGTH, 0);
		if(nrecv > 0)
		{
			recvBuff[nrecv] = 0;
			printf(">%s\n", recvBuff);
		}
		else if(nrecv == SOCKET_ERROR)
		{
			//user->connOK = false;
			//closesocket(user->sock);
			printf("Disconnected from the %s!\n", inet_ntoa(user->addr.sin_addr));
			user->endTalk();
			//return 1;
		}
	}
	return EXIT_SUCCESS;
}

void User::reciver()
{
	hThread = CreateThread(NULL, 0, wait_for_msg, (LPVOID*)this, 0, NULL);
}

void User::startTalk()
{
	while(!connOK)
	{
		Sleep(10);
		continue;
	}
	//reciver
	//hThread = CreateThread(NULL, 0, wait_for_msg, (LPVOID*)this, 0, NULL);
	reciver();

	//sender
	while (true)
	{
		//DWORD exitCode;
		////check whether reciver end.  and restart reciver thread.
		//if(GetExitCodeThread(hThread, &exitCode) != STILL_ACTIVE && connOK)
		//	hThread = CreateThread(NULL, 0, wait_for_msg, (LPVOID*)this, 0, NULL);

		int nsend;
		char sendBuff[LENGTH];
		sprintf(sendBuff, "%s: ", name);
		gets(sendBuff+strlen(sendBuff));

		nsend = send(sock, sendBuff, strlen(sendBuff), 0);
		if(nsend != strlen(sendBuff))
		{
			printf("send error, Do you reconnect?(Y/N)\n");

			gets(sendBuff);
			if(sendBuff[0] == 'Y')
				init(port, inet_ntoa(addr.sin_addr));
		}

		Sleep(10);
	}
	//closesocket(sock);
	endTalk();
}
void User::initAddr(int port, char* ip)
{

	if(!ip)
		addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	else
		addr.sin_addr.S_un.S_addr = inet_addr(ip);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
}

void User::endTalk()
{
	connOK = false;
	closesocket(sock);
}

void User::printHostIp()
{
	char hostName[255];
	char *ip;
	PHOSTENT hostinfo;

	gethostname(hostName, sizeof(hostName));

	hostinfo = gethostbyname(hostName);

	printf("Your all IP address are\n");

	for(int i = 0; hostinfo->h_addr_list[i]; i++)
	{
		ip = inet_ntoa(*(in_addr*) hostinfo->h_addr_list[i]);
		printf("  %s\n" ,ip);
	} 

	printf("Your friends can connect one of the above.\n");

}